import React, { useState } from 'react';
import styles from './index.less';
import { Button, message, Spin } from 'antd';
import { useSetState } from 'ahooks';
import { connect } from 'umi';

import { TRAlert, TRDefault } from '#/components/index.js';
import { HttpCode } from '#/utils/contacts.js';

import { getDealElementOptions, havePermissions } from './tool';
import {
  postQueryLongLatConfigList,
  postRemoveLongLatConfigList,
  postSaveLongLatConfigList,
  postUpdateLongLatConfigList,
  queryMarketList,
} from './service';
import type {
  IApplyType,
  IDataSourceType,
  IDealElementOptions,
  IProps,
  IStationsData,
} from './type';
import { IOperationType, IStationLongitudeLatitudeConfigPermissions } from './type';
import { ApplyModal, List } from './components/index';
// @ts-ignore
import { getTreeByCodes } from '@/utils';

const StationLongitudeLatitudeConfig = (props: IProps) => {
  const { buttonPermissions, menuCode } = props;
  const [dataSource, setDataSource] = useState<IDataSourceType[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true); // 列表是否加载中；
  const [isError, setIsError] = useState<boolean>(false); // 列表是否报错态
  const [provinceOptions, setProvinceOptions] = useState<IDealElementOptions[]>([]); // 省份数据
  const [groupOptions, setGroupOptions] = useState<IDealElementOptions[]>([]); // 集团数据
  const [stationData, setStationData] = useSetState<IStationsData>({
    dealElementOptions: [],
    dealElementModalOptions: [],
    dealElementDataObj: {},
  }); // 交易单元列表

  // 初始化获取数据
  const fetchData = async () => {
    setIsLoading(true);
    const res: any = await postQueryLongLatConfigList({ needPermission: false, menuCode });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setDataSource(res?.data || []);
      setIsError(false);
    } else {
      message.error(res?.message || '查询失败');
      setIsError(true);
    }
    setIsLoading(false);
  };

  const getStationData = async () => {
    const res = await queryMarketList(menuCode);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
      setProvinceOptions(power || []);
      let _groupOptions: any[] = [];
      (power || []).forEach((item: any) => {
        _groupOptions = [..._groupOptions, ...(item?.children || [])];
      });
      setGroupOptions(_groupOptions);
      const _dealElementResultData = getDealElementOptions(power || []);
      const _data: IStationsData = {
        dealElementOptions: _dealElementResultData?.value || [],
        // @ts-ignore
        dealElementModalOptions: _dealElementResultData?.modalData || [],
        dealElementDataObj: _dealElementResultData.dataObj,
      };
      setStationData(_data);
    } else {
      setStationData({
        dealElementOptions: [],
        dealElementModalOptions: [],
        dealElementDataObj: {},
      });
    }
  };

  React.useEffect(() => {
    fetchData();
    getStationData();
  }, []);

  // 新增
  const onAdd = async (operationType: IOperationType, data?: IDataSourceType) => {
    let resoult;
    if (operationType === IOperationType.ADD) {
      resoult = havePermissions(
        IStationLongitudeLatitudeConfigPermissions.STATIONLONGITUDELATITUDECONFIGSAVE,
        buttonPermissions,
      );
      if (resoult) {
        const result: any = await ApplyModal.show({
          operationType,
          data,
          stationData: stationData,
          provinceOptions,
          groupOptions,
          onOk: async (val: IApplyType) => {
            const res: any = await postSaveLongLatConfigList(val);
            if (res && res.statusCode === HttpCode.SUCCESS) {
              message.success('保存成功');
            } else {
              message.error(res?.message || operationType);
            }
            return res;
          },
        });
        if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
          fetchData();
        }
      }
    } else {
      resoult = havePermissions(
        IStationLongitudeLatitudeConfigPermissions.STATIONLONGITUDELATITUDECONFIGUPDATE,
        buttonPermissions,
      );
      if (resoult) {
        const result: any = await ApplyModal.show({
          operationType,
          data,
          stationData: stationData,
          provinceOptions,
          groupOptions,
          onOk: async (val: IApplyType) => {
            const res: any = await postUpdateLongLatConfigList(val);
            if (res && res.statusCode === HttpCode.SUCCESS) {
              message.success('保存成功');
            } else {
              message.error(res?.message || operationType);
            }
            return res;
          },
        });
        if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
          fetchData();
        }
      }
    }
  };

  // 删除配置
  const onDetele = async (data: IDataSourceType) => {
    const resoult = havePermissions(
      IStationLongitudeLatitudeConfigPermissions.STATIONLONGITUDELATITUDECONFIGREMOVE,
      buttonPermissions,
    );
    if (resoult) {
      const resq = await TRAlert.show('是否确认删除');
      if (resq.index === 1) {
        const res: any = await postRemoveLongLatConfigList({ id: data?.id });
        if (res && res.statusCode === HttpCode.SUCCESS) {
          message.success('删除成功');
          fetchData();
        } else {
          message.error('删除失败');
        }
      }
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <div className={styles.header}>
          <div className={styles.title}>交易单元经纬度维护</div>
          <Button
            type="primary"
            className={styles.button}
            onClick={() => onAdd(IOperationType.ADD)}
          >
            新增
          </Button>
        </div>
        <div className={styles.bottom}>
          {isLoading ? (
            <Spin className={styles.spin} />
          ) : isError ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : dataSource?.length > 0 ? (
            <List dataSource={dataSource} onDetele={onDetele} onEdit={onAdd} />
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ stationLongitudeLatitudeConfig, global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  stationLongitudeLatitudeConfig,
}))(StationLongitudeLatitudeConfig);
